package fun.shuofeng.myspringmvc.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 统一拦截所有请求，设置编码为UTF-8
 *
 * @author 朔风
 * @date 2023-11-07 09:28
 */

public class SecurityFilter extends HttpFilter {

    private final Logger logger = LoggerFactory.getLogger(SecurityFilter.class);
    public String[] excludedPathArray;


    @Override
    public void init(FilterConfig config) {
        String excludedPath = config.getInitParameter("excludedPath");
        if (Objects.nonNull(excludedPath) && !excludedPath.isEmpty()) {
            excludedPathArray = excludedPath.split(",");
        }

    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response,
                            FilterChain chain) throws IOException, ServletException {
        logger.info("拦截操作==============");
        // 设置请求头编码
        request.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        // 设置响应头编码
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        // 做放行操作
        String pathInfo = request.getPathInfo();
        logger.info("当前请求路径：{}", pathInfo);
        for (String path : excludedPathArray) {
            if (pathInfo.equals(path)) {
                // 如果匹配到排查的路径就放行
                chain.doFilter(request, response);
                return;
            }
        }
        try {
            doChain(request, response, chain);
        } catch (Exception e) {
            logger.warn(e.getMessage());
            e.printStackTrace();
        }
        logger.info("放行操作==============");
    }

    public void doChain(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws Exception {
        // 用于子类实现
    }


}
